package cn.itcast.listener;

import cn.itcast.utils.MailUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.stereotype.Component;


/**
 * 邮件消费监听器msgConsumerListener负责监听RabbitMQ队列中的消息，
 * 将消息整理成邮件发送
 */
@Component("msgConsumerListener")
@Log4j
public class MessageConsumerListener implements MessageListener {


    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void onMessage(Message message) {

        try {

            JsonNode jsonNode = MAPPER.readTree(message.getBody());

            String email = jsonNode.get("email").asText();
            String subject = jsonNode.get("subject").asText();
            String content = jsonNode.get("content").asText();

            log.info("获取队列中消息：" + email);
            log.info("获取队列中消息：" + subject);
            log.info("获取队列中消息：" + content);

            // 发邮件
            MailUtil.sendMsg(email, subject, content);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }





}
